<template>
  <el-dialog
    :title="typeText == 'updata' ? `${t('keys.Amend')}${sourType == 'phone' ? t('keys.address_tel') : t('keys.Mailbox')}` : `${sourType == 'phone' ? t('keys.address_tel') : t('keys.Mailbox')}${t('keys.Verifiy')}`"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    width="400px"
  >
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="0" class="demo-ruleForm" label-position="left" v-if="dialogVisible">
      <el-form-item prop="telephone" :error="errorTips.telephone" class="pofixd" v-if="sourType == 'phone'">
        <el-input
          v-model="ruleForm.telephone"
          :placeholder="t('keys.Please_new_phone')"
          maxlength="11"
          oninput="value=value.replace(/[^\d]/g,'')"
          :disabled="typeText == 'verify'"
          style="width: 99%"
        />
      </el-form-item>
      <el-form-item prop="email" :error="errorTips.email" class="pofixd" v-else>
        <el-input v-model.trim="ruleForm.email" type="text" :disabled="typeText == 'verify'" :placeholder="t('keys.Please_new_email')" clearable> </el-input>
      </el-form-item>
      <el-form-item prop="code" :error="errorTips.code">
        <el-input
          v-model.trim="ruleForm.code"
          type="text"
          maxlength="6"
          :placeholder="t('keys.Verification_Code')"
          oninput="if(value.length>8)value=value.slice(0,8)"
          style="width: 63%"
          clearable
        >
        </el-input>
        <el-button style="width: 36%" :disabled="smsObj.count != 0" plain @click.stop="sendSms">{{ smsObj.content }}</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ t('keys.cancel') }}</el-button>
        <el-button type="primary" @click="handelSubmit(ruleFormRef)">{{ t('keys.ok') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { validatePhone, validateEmail } from 'utils/validate.js'
import { accountCaptchaApi, modifyAccountApi, postPhoneValidateApi, getPhoneValidateApi } from 'api/home'
import { ERR_OK, ERR_FORM_CODE } from 'config/statusCode'
const { t } = useI18n() // 中英文
const emit = defineEmits(['refresh'])
const ruleFormRef = ref()
const checkPhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t('keys.phone_cant_empty')))
  }
  setTimeout(() => {
    if (!Number.isInteger(+value)) {
      callback(new Error(t('keys.please_enter_number_tips')))
    } else {
      if (validatePhone(value)) {
        callback()
      } else {
        callback(new Error(t('keys.reg_tele_empty_format_tips')))
      }
    }
  }, 100)
}
var checkEmail = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t('keys.email_empty')))
  } else {
    if (validateEmail(value)) {
      callback()
    } else {
      callback(new Error(t('keys.email_vis_empty')))
    }
  }
}

const ruleForm = ref({
  telephone: '',
  email: '',
  code: ''
})

const rules = reactive({
  telephone: [{ required: true, validator: checkPhone, trigger: ['blur', 'change'] }],
  email: [{ validator: checkEmail, trigger: ['blur', 'change'] }],
  code: [{ required: true, message: t('keys.captchaCodePlaceholder'), trigger: 'blur' }]
})

const typeText = ref('')
const sourType = ref('phone')
const dialogVisible = ref(false)
const showDialog = (type, sType, res) => {
  ruleForm.value.telephone = type == 'updata' ? '' : res?.phone
  ruleForm.value.email = type == 'updata' ? '' : res?.email
  ruleForm.value.code = ''
  dialogVisible.value = true
  typeText.value = type
  sourType.value = sType
}

// 后端返回验证错误信息
const errorTips = ref({
  telephone: '',
  email: '',
  code: ''
})
const initErrorTips = () => {
  for (var key in errorTips.value) {
    errorTips.value[key] = ''
  }
}

const smsObj = reactive({
  content: t('keys.Get_verification_code'),
  count: 0,
  timerSms: null
})

// 发送验证码
const sendSms = () => {
  if (smsObj.count > 0) {
    return
  }
  if (!(sourType.value == 'phone' && typeText.value == 'verify')) {
    // 校验手机号
    if (sourType.value == 'phone') {
      if (!ruleForm.value.telephone) {
        ElMessage.error(t('keys.phonePlaceholder'))
        return
      }
      if (!validatePhone(ruleForm.value.telephone)) {
        ElMessage.error(t('keys.Please_enter_the_correct_mobile_number'))
        return
      }
    } else {
      if (!ruleForm.value.email) {
        ElMessage.error(t('keys.emailPlaceholder'))
        return
      }
      if (!validateEmail(ruleForm.value.email)) {
        ElMessage.error(t('keys.emailokPlaceholder'))
        return
      }
    }
  }
  let param = {
    number: sourType.value == 'phone' ? ruleForm.value.telephone : ruleForm.value.email,
    type: sourType.value == 'phone' ? 'SMS' : 'EMAIL'
  }
  let aprUrl = sourType.value == 'phone' && typeText.value == 'verify' ? getPhoneValidateApi : accountCaptchaApi
  // 请求后台发送验证码至手机
  aprUrl(sourType.value == 'phone' && typeText.value == 'verify' ? '' : param).then((res) => {
    if (res.code === ERR_OK) {
      ElMessage.success(t('keys.Verification_code_has_been_sent'))
      // 控制倒计时及按钮是否可以点击
      const TIME_COUNT = 60
      smsObj.count = TIME_COUNT
      smsObj.timerSms = window.setInterval(() => {
        if (smsObj.count > 0 && smsObj.count <= TIME_COUNT) {
          // 计时秒数
          smsObj.count--
          // 更新按钮的文字内容
          smsObj.content = smsObj.count + 's' + t('keys.Reacquire_after')
        } else {
          smsObj.content = t('keys.Get_verification_code')
          // 清空定时器!!!
          clearInterval(smsObj.timerSms)
          smsObj.timerSms = null
        }
      }, 1000)
    }
  })
}

const handelSubmit = async (ruleFormRef) => {
  initErrorTips()
  if (!ruleFormRef) return
  await ruleFormRef.validate(async (valid, fields) => {
    if (valid) {
      let apiUrl = typeText.value == 'updata' ? modifyAccountApi : postPhoneValidateApi
      let params = {
        captcha: ruleForm.value.code,
        number: sourType.value == 'phone' ? ruleForm.value.telephone : ruleForm.value.email,
        type: sourType.value == 'phone' ? 'SMS' : 'EMAIL'
      }
      let phoneForm = {
        code: ruleForm.value.code,
        telephone: ruleForm.value.telephone
      }
      const { code, desc, data } = await apiUrl(typeText.value == 'updata' ? params : phoneForm)
      if (code === ERR_OK) {
        ElMessage({
          message: t('keys.Validation_succeeded'),
          type: 'success'
        })
        emit('refresh')
        dialogVisible.value = false
      } else if (code === ERR_FORM_CODE) {
        // errorTips.value = data || {}
        ElMessage.error(desc)
      }
    }
  })
}
defineExpose({
  showDialog
})
</script>
